package com.tungse.study.mini_spring.web;

import com.tungse.study.mini_spring.annotation.MyAutowired;
import com.tungse.study.mini_spring.annotation.MyComponent;
import com.tungse.study.mini_spring.annotation.MyPostConstruct;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.io.File;
import java.io.IOException;
import java.util.logging.LogManager;

/**
 * @author Tungse
 */
@MyComponent
public class TomcatServer {

    @MyAutowired
    private DispatcherServlet dispatcherServlet;

    @MyPostConstruct
    public void start() throws LifecycleException {

        LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        int port = 8080;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context context = tomcat.addContext(contextPath, docBase);;

        tomcat.addServlet(contextPath, "dispatcherServlet", dispatcherServlet);

        context.addServletMappingDecoded("/*", "dispatcherServlet");
        tomcat.start();
        System.out.println("tomcat started at port " + port);
    }
}
